﻿#include "SerialPortManager.h"

#include "LogSaver.h"
#include <qdebug.h>

SerialPortManager::SerialPortManager(QObject* parent):QSerialPort(parent)
{
  initSerialPort();
  serialPortListenerState = false;
}
SerialPortManager::~SerialPortManager()
{
  slot_closeListener();
  disconnect();
}
bool SerialPortManager::slot_sendData(QByteArray data)//发送数据
{
  if (!isOpen())
    {
      logSaver->saveLog(QStringLiteral("%1：串口发送数据失败：串口未打开").arg(objectName()), LogSaver::Debug);
      return false;
    }
  if (write(data) == -1)
    {
      logSaver->saveLog(QStringLiteral("%1：串口发送数据失败：写入数据失败").arg(objectName()), LogSaver::Debug);
      return false;
    }
  flush();
  logSaver->saveLog(QStringLiteral("%1：串口发送数据成功：%2").arg(objectName()).arg((QString)data.toHex()), LogSaver::Debug);
  return true;
}
bool SerialPortManager::slot_openListener()//打开串口监听器
{
  if (!open(QSerialPort::ReadWrite))
    {
      logSaver->saveLog(QStringLiteral("%1：打开串口监听失败").arg(objectName()), LogSaver::Information);
      return false;
    }
  if (!serialPortListenerState)
    {
      disconnect(this, &QSerialPort::readyRead, this, &SerialPortManager::slot_ReadData);
      connect(this, &QSerialPort::readyRead, this, &SerialPortManager::slot_ReadData);
      serialPortListenerState = true;
      logSaver->saveLog(QStringLiteral("%1：打开串口监听成功").arg(objectName()), logSaver->Information);
      return true;
    }
  else
    {
      return false;
    }
}
void SerialPortManager::slot_closeListener()//关闭串口监听器
{
  if (!serialPortListenerState)
    {
      return;
    }
  disconnect(this, &QSerialPort::readyRead, this, &SerialPortManager::slot_ReadData);
  serialPortListenerState = false;
  close();
  logSaver->saveLog(QStringLiteral("%1：关闭串口监听成功").arg(objectName()), LogSaver::Information);
  return;
}
bool SerialPortManager::isListening()
{
  return serialPortListenerState;
}
void SerialPortManager::slot_ReadData()//接收数据
{
  QByteArray data = readAll();
  emit signal_dataReceived(data);
  logSaver->saveLog(QStringLiteral("%1：串口收到数据：%2").arg(objectName()).arg((QString)data.toHex()), LogSaver::Debug);
}
void SerialPortManager::initSerialPort()
{
  setPortName("COM1");//端口号
  setBaudRate(9600);//波特率
  setParity(QSerialPort::NoParity);//校验位
  setDataBits(QSerialPort::Data8);//数据位
  setStopBits(QSerialPort::OneStop);//停止位
  setFlowControl(QSerialPort::NoFlowControl);//流控制
}

LogSaver* SerialPortManager::getLogSaver()
{
  return logSaver;
}
void SerialPortManager::setLogSaver(LogSaver* logSaver)
{
  this->logSaver = logSaver;
}
